<template>
  <div>
    <header
      style="
        display: flex;
        margin-bottom: -0.5%;
        justify-content: space-between;
      "
    >
      <h1>仿真结果查询</h1>
      <div>
        <el-button
          type="primary"
          style="
            margin-right: 20px;
            margin-top: -3px;
            height: 35px;
            font-size: 18px;
            background-color: #595959;
          "
          @click="back"
        >返回上一页
        </el-button
        >
      </div>
    </header>
    <el-main
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
    >
      <el-col style="width: 100%; margin-top: -1.5%; margin-bottom: 0.5%">
        <el-header>查询排序统计报表</el-header>
      </el-col>
      <div
        style="
          width: 80%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <a style="width: 200px; margin-right: -10px; font-size: 20px"
        >选择仿真类型：</a
        >
        <el-select
          v-model="selectedType1"
          placeholder="请选择仿真类型"
          size="large"
          style="width: 35%"
        >
          <el-option
            v-for="item in result0"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          size="large"
          style="margin-left: 2%; background-color: #003f82"
          @click="sendLineInfoSequentially"
        >查询电压时序图
        </el-button
        >
        <el-button
          type="primary"
          size="large"
          style="background-color: #595959; margin-left: 2.5%"
          @click="reset"
        >重置
        </el-button
        >
      </div>
      <div
        style="
          width: 100%;
          justify-content: center;
          display: flex;
          flex-direction: column;
          align-items: center;
        "
      >
        <div style="width: 80%; display: flex">
          <div>
            <el-button v-if="isShowTable" link @click="toggleInverseSelection">
              <el-tag type="success" size="large" style="width: 100%"
              >反 选
              </el-tag
              >
            </el-button>
            <el-button
              v-if="isShowTable"
              link
              @click="removeAll"
              style="margin-left: 0"
            >
              <el-tag type="warning" size="large" style="width: 100%"
              >取消选中
              </el-tag
              >
            </el-button>
          </div>
          <el-button
            v-if="isShowTable"
            link
            @click="SelectionAll"
            style="margin-left: 5px"
          >
            <el-tag type="primary" size="large" style="width: 100%"
            >全选
            </el-tag
            >
          </el-button>
        </div>
        <el-table
          v-if="isShowTable"
          ref="table"
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange"
          border
          max-height="350px"
          :data="curves"
          style="width: 80%"
        >
          <el-table-column
            type="selection"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column label="序号" width="100" align="center">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="曲线名"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
      <el-col style="width: 100%; margin-top: 10px">
        <el-card style="margin-top: 10px; padding: 5px">
          <el-header>
            <div style="display: flex; justify-content: space-between">
              <div>
                <el-button
                  v-if="isShowTable"
                  link
                  @click="minTable"
                  style="margin-left: 5px"
                >
                  <el-tag type="primary" size="large" style="width: 100%"
                  >最小化表格
                  </el-tag
                  >
                </el-button>
                <el-button
                  v-if="!isShowTable"
                  link
                  @click="maxTable"
                  style="margin-left: 5px"
                >
                  <el-tag type="primary" size="large" style="width: 100%"
                  >最大化表格
                  </el-tag
                  >
                </el-button>
                <span>指定参数返回电压时序图</span>
              </div>
              <div style="display: flex">
                <!-- 下拉框选择画布 -->
                <el-select
                  style="width: 180px; margin-right: 10px"
                  v-model="selectedPlot"
                >
                  <el-option
                    v-for="i in visiblePlotCount"
                    :key="i"
                    :value="'plot' + i"
                    :label="'画布' + i"
                  ></el-option>
                </el-select>
                <!-- 增加画布选项 -->
                <el-button
                  type="primary"
                  @click="addPlotOption"
                  :disabled="visiblePlotCount >= 10"
                  style="background-color: #333333"
                >增加画布
                </el-button
                >
                <el-button
                  type="primary"
                  @click="clearPlot"
                  style="background-color: #595959"
                >清空画布
                </el-button
                >
              </div>
            </div>
          </el-header>
          <el-scrollbar max-height="750px">
            <div
              style="width: 100%"
              v-for="i in visiblePlotCount"
              :key="i"
              :id="'bokeh-plot' + i"
            ></div>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-main>
  </div>
</template>

<script setup>
import { onActivated, ref, onMounted, defineProps, onUnmounted } from "vue";
import { getAllType, getAllLineName, getPlotWave } from "@/server/results";
import router from "@/router/index.js";
import mitt from "mitt";

const back = () => {
  router.back();
};
const props = defineProps({
  rowData: Object
});
const rowData1 = ref(null);

const reset = () => {
  router.go(0);
};
const result0 = ref([]);
const result1 = ref([]);
const selectedType1 = ref("");
const getType = async () => {
  try {
    const response = await getAllType(rowData1.value);
    result0.value = response;
  } catch (e) {
    console.error("e:", e);
  }
};

const getAllLine = async () => {
  try {
    const response = await getAllLineName({
      circuit_diagram_name: rowData1.value.circuit_diagram_name
    });
    result1.value = response;
    curves.value = response.map((name, index) => ({
      index: index + 1,
      name
    }));
    console.log(response);
    console.log(curves.value);
  } catch (e) {
    console.error("e:", e);
  }
};

const isShowTable = ref(true);
const minTable = () => {
  isShowTable.value = false;
};
const maxTable = () => {
  isShowTable.value = true;
};

const selectedPlot = ref("plot1");
const plots = ref({
  plot1: ref(null),
  plot2: ref(null)
}); // 初始化两个画布
const clearPlot = () => {
  // 遍历plots对象中的所有画布
  for (const plotId in plots.value) {
    const plotElement = document.getElementById(
      `bokeh-plot${plotId.slice(-1)}`
    );
    if (plotElement) {
      plotElement.innerHTML = "";
    }
    // 重置画布引用
    plots.value[plotId] = null;
  }
  // 重置其他状态变量
  visiblePlotCount.value = 2;
};
const draw_bokeh = (plot, all_data, plotIndex, color) => {
  const { voltage, time, title } = all_data;
  let show = false;
  if (!plot) {
    plot = window.Bokeh.Plotting.figure({
      title: title,
      x_axis_label: "时间",
      y_axis_label: "电压",
      tools: "pan,crosshair,wheel_zoom,box_zoom,reset,save",
      height: window.innerHeight / 3,
      width: (window.innerWidth / 5) * 4
    });

    const { HoverTool } = window.Bokeh;
    const hover = new HoverTool({
      tooltips: [
        ["电压值", "@voltage"],
        ["时间", "@time"],
        ["名称", "@title"]
      ],
      mode: "mouse" // Hover mode
    });
    plot.add_tools(hover);
    show = true;
  }

  let titles = [];
  for (let i = 0; i < time.length; ++i) {
    titles.push(title);
  }

  const source = new window.Bokeh.ColumnDataSource({
    data: { time: time, voltage: voltage, title: titles }
  });

  // 添加曲线到图表
  plot.line(
    { field: "time" },
    { field: "voltage" },
    { source: source, line_width: 2, line_color: color }
  );

  // 渲染图表到页面
  if (show) {
    const plotElement = document.getElementById(`bokeh-plot${plotIndex}`);
    if (plotElement) {
      window.Bokeh.Plotting.show(plot, plotElement);
    } else {
      console.error(`Element with id bokeh-plot${plotIndex} not found`);
    }
  }
  return plot;
};
const getRandomColor = () => {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
};

const visiblePlotCount = ref(2); // 默认显示两个画布

const addPlotOption = () => {
  if (visiblePlotCount.value < 10) {
    const isconfirm = confirm("是否增加画布");
    if (isconfirm) {
      const newPlotId = `plot${visiblePlotCount.value + 1}`;
      plots.value[newPlotId] = ref(null); // 添加新的画布引用
      visiblePlotCount.value++;
    }
  }
};

onActivated(() => {
  selectedType1.value = "";
  result0.value = [];
  curves.value = [];
  removeAll();

  rowData1.value = [];
  if (props.rowData) {
    rowData1.value = props.rowData;
  }
  getType();
  getAllLine();
});

onMounted(() => {
  if (props.rowData) {
    rowData1.value = props.rowData;
  }
  getType();
  getAllLine();
  window.addEventListener("keydown", handleKeyDown);
  window.addEventListener("keyup", handleKeyUp);
  emitter.on("row-click", handleRowClick);
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);
  window.removeEventListener("keyup", handleKeyUp);
  emitter.off("row-click", handleRowClick);
});
/* ------------------------------------------------ */
const selectedCurves = ref([]);
const showCurveListDialog = ref(false);
const curves = ref([]);
const selectedCurvesInDialog = ref([]);

const confirmCurveSelection = () => {
  console.log("confirmCurveSelection");
  selectedCurves.value = selectedCurvesInDialog.value.map((item) =>
    curves.value.find((curve) => curve.name === item.name)
  );
  // 设置currentIndex为选中曲线的第一个索引
  currentIndex.value = curves.value.findIndex(
    (curve) => curve.name === selectedCurves.value[0]?.name
  );
  showCurveListDialog.value = false;
};

/*-------------递归调用-----------------------*/
const currentIndex = ref(0);
let startIndex = 0;
const sendLineInfoSequentially = async () => {
  console.log(startIndex);
  // console.log(selectedCurves.value);
  if (startIndex < selectedCurves.value.length) {
    const lineInfo = selectedCurves.value[startIndex];
    try {
      const plotIndex = selectedPlot.value.slice(-1);
      const response = await getPlotWave({
        ...rowData1.value,
        type: selectedType1.value,
        line_info: lineInfo.name
      });
      const color = getRandomColor();
      plots.value[selectedPlot.value] = draw_bokeh(
        plots.value[selectedPlot.value],
        response,
        plotIndex,
        color
      );
      // 更新索引
      startIndex++;
      // 递归调用
      await sendLineInfoSequentially();
    } catch (e) {
      console.error("Error sending line_info:", e);
      startIndex = selectedCurves.value.length;
    }
  } else {
    startIndex = 0;
    console.warn("代码结束");
  }
};

const emitter = mitt();
const lastSelectedIndex = ref(-1);
const isShiftPressed = ref(false);
const handleKeyDown = (event) => {
  if (event.key === "Shift") {
    isShiftPressed.value = true;
  }
};

const handleKeyUp = (event) => {
  if (event.key === "Shift") {
    isShiftPressed.value = false;
  }
};

const handleRowClick = (row) => {
  if (table.value) {
    const currentIndex = curves.value.indexOf(row);
    if (isShiftPressed.value && lastSelectedIndex.value !== -1) {
      const startIndex = Math.min(lastSelectedIndex.value, currentIndex);
      const endIndex = Math.max(lastSelectedIndex.value, currentIndex);
      const selectedRows = table.value.getSelectionRows();
      const selectionMap = curves.value.reduce((map, item) => {
        map[curves.value.indexOf(item)] = selectedRows.includes(item);
        return map;
      }, {});
      table.value.toggleRowSelection(
        curves.value[startIndex],
        selectionMap[startIndex]
      );
      for (let i = startIndex + 1; i < endIndex; i++) {
        table.value.toggleRowSelection(curves.value[i], !selectionMap[i]);
      }
      table.value.toggleRowSelection(
        curves.value[endIndex],
        !selectionMap[endIndex]
      );
    } else {
      table.value.toggleRowSelection(row);
    }
    lastSelectedIndex.value = currentIndex;
  }
};

const table = ref(null);
const selectedRows = ref([]);
const handleSelectionChange = (rows) => {
  selectedCurvesInDialog.value = rows;
  selectedRows.value = rows;
  confirmCurveSelection();
};
// 反选函数
const toggleInverseSelection = () => {
  if (!table.value) return;
  // 获取所有行
  const allRows = curves.value;
  allRows.forEach((row) => {
    table.value.toggleRowSelection(row, !selectedRows.value.includes(row));
  });
};
// 取消函数
const removeAll = () => {
  if (!table.value) return;
  // 获取所有行
  const allRows = curves.value;
  allRows.forEach((row) => {
    table.value.toggleRowSelection(row, false);
  });
  selectedRows.value = [];
};
// 全选函数
const SelectionAll = () => {
  if (!table.value) return;
  const allRows = curves.value;
  allRows.forEach((row) => {
    table.value.toggleRowSelection(row, true);
  });
  selectedRows.value = [...allRows];
};
</script>

<style scoped="scss">
.plot {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
}

.flex-column {
  flex: 1 1 50%;
  /* 两个列各占50%宽度 */
  display: flex;
  /* 使每个列内的项目垂直排列 */
  flex-direction: column;
  /* 列方向为垂直 */
}

.flex-item {
  margin: 10px;
}

.span-style {
  margin-top: -5px;
  margin-bottom: -2px;
  font-size: 18px;
}

.table-header {
  background-color: black;
}

.inputStyle {
  width: 850px;
}

table {
  div {
    cursor: pointer;
  }
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}

.el-divider {
  margin-top: 10px;
  margin-bottom: -10px;
}
</style>
